package com.simpleplayer.services;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class UriUtil {
    /**
     * 根据 uri 后缀判断 uri 的 mime 类型
     * @param uri uri 路径
     * @return 返回 uri 的 mime 类型，无法识别会返回 "text/plain"
     */
    public static String getMimeType(String uri) {
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                Path source = Paths.get(uri);
                return Files.probeContentType(source);
            } else {
                return guesssMimeTypeByName(uri);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private static String guesssMimeTypeByName(String uri) {
        String mime = null;

        if (uri.endsWith(".mp4")) {
            mime = "video/mp4";
        } else if (uri.endsWith(".webm")) {
            mime = "video/webm";
        } else if (uri.endsWith(".avi")) {
            mime = "video/x-msvideo";
        } else if (uri.endsWith(".flv")) {
            mime = "video/x-flv";
        } else if (uri.endsWith(".mpg") || uri.endsWith(".mpe") || uri.endsWith(".mpeg")) {
            mime = "video/mpeg";
        } else if (uri.endsWith(".qt") || uri.endsWith(".mov")) {
            mime = "video/quicktime";
        } else if (uri.endsWith(".m4v")) {
            mime = "video/x-m4v";
        } else if (uri.endsWith(".wmv")) {
            mime = "video/x-ms-wmv";
        } else if (uri.endsWith(".png")) {
            mime = "data:image/png;base64,";
        } else if (uri.endsWith(".jpg") || uri.endsWith(".jpeg")) {
            mime = "data:image/jpg;base64,";
        } else if (uri.endsWith(".gif")) {
            mime = "data:image/gif;base64,";
        }

        return mime;
    }

    /**
     * 将一段URL编码转为中文
     * @param str 要解码的字符串
     * @return 解码后的字符串，发生异常返回原字符串
     */
    public static String chinesize(String str) {
        try {
            return URLDecoder.decode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return str;
    }
}
